package com.ruoyi.boat.aop;

import com.ruoyi.boat.utils.DateUtil;
import com.ruoyi.common.core.domain.BaseEntity;
import com.ruoyi.common.utils.StringUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;

import java.util.Date;

@Aspect
@Component
public class SQLFilterAspect {

    public static final String SQL_FILTER = "sqlFilter";

    @Before("@annotation(sqlFilter)")
    public void doBefore(JoinPoint joinPoint, SQLFilter sqlFilter) {
        clearDataScope(joinPoint);

        Object params = joinPoint.getArgs()[0];
        if (StringUtils.isNotNull(params) && params instanceof BaseEntity) {
            BaseEntity baseEntity = (BaseEntity) params;
            String beginTime = (String) baseEntity.getParams().get("beginTime");
            String endTime = (String) baseEntity.getParams().get("endTime");
            String ids = (String) baseEntity.getParams().get("ids");

            String sqlString = "";

            // 时间区间查询
            if (beginTime != null && !beginTime.isEmpty()) {
                Date date = DateUtil.stringToDate(beginTime, null);
                if (date != null) sqlString += String.format(" and %s >= '%s'", sqlFilter.timeColumn(), beginTime);
            }
            if (endTime != null && !endTime.isEmpty()) {
                Date date = DateUtil.stringToDate(endTime, null);
                if (date != null) sqlString += String.format(" and %s <= '%s'", sqlFilter.timeColumn(), endTime);
            }

            // id查询
            if (ids != null && !ids.isEmpty()) {
                sqlString += String.format(" and id in (%s)", ids);
            }

            if (!sqlString.isEmpty()) {
                baseEntity.getParams().put(SQL_FILTER, sqlString);
            }
        }
    }

    /**
     * 拼接权限sql前先清空params.dataScope参数防止注入
     */
    private void clearDataScope(final JoinPoint joinPoint) {
        Object params = joinPoint.getArgs()[0];
        if (StringUtils.isNotNull(params) && params instanceof BaseEntity) {
            BaseEntity baseEntity = (BaseEntity) params;
            baseEntity.getParams().put(SQL_FILTER, "");
        }
    }

}
